// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {frameUpdate} from "../frame/FrameUtils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Timer extends cc.Component {

  label: cc.Label = null;

  private countdown = 300;

  // LIFE-CYCLE CALLBACKS:

  onLoad() {
    this.label = this.getComponent(cc.Label);
    this.enabled = false;
    // this.startTimer()
    this.updateLabel();
  }

  public startTimer(cd = 300) {
    this.countdown = cd;
    this.enabled = true;
  }

  private updateLabel() {
    this.label.string = this.formatCountdown();
  }

  private formatCountdown(): string {
    const cd = Math.floor(this.countdown)
    let s = cd % 60;
    let m = Math.floor(cd / 60);
    return `${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`
  }

  @frameUpdate()
  updateFixedFrame(dt) {
    this.countdown -= dt;
    if (this.countdown <= 0) {
      this.countdown = 0;
      this.enabled = false;
      this.node.emit('timerEnd')
    }
    this.updateLabel();
  }
}
